<template>
    <div class="page-container">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span class="title">入库管理</span>
                </div>
            </template>
            
            <!-- 搜索区域 -->
            <div class="search-area">
                <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                    <el-form-item label="订单编号">
                        <el-input 
                            v-model="searchForm.orderNo" 
                            placeholder="请输入订单编号" 
                            clearable 
                            prefix-icon="Search"
                            class="custom-input"
                        />
                    </el-form-item>
                    <el-form-item label="入库时间">
                        <el-date-picker
                            v-model="searchForm.dateRange"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="YYYY-MM-DD"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch" class="search-button">
                            <el-icon><Search /></el-icon>搜索
                        </el-button>
                        <el-button @click="resetForm" class="reset-button">
                            <el-icon><Refresh /></el-icon>重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 表格区域 -->
            <el-table 
                :data="tableData" 
                style="width: 100%" 
                border 
                stripe
                :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
                :row-style="{ height: '60px' }"
                :cell-style="{ padding: '8px 0' }"
                highlight-current-row
            >
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="序号" width="80" type="index" align="center" />
                <el-table-column prop="orderNo" label="订单编号" min-width="150" align="center" show-overflow-tooltip />
                <el-table-column prop="supplier" label="供应商名称" min-width="120" align="center" show-overflow-tooltip />
                <el-table-column prop="operator" label="入库人" width="120" align="center" />
                <el-table-column label="状态" width="120" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.status === '已完成' ? 'success' : 'warning'">
                            {{ row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="stockInTime" label="入库时间" min-width="180" align="center" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ formatDate(row.stockInTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center" fixed="right">
                    <template #default="{ row }">
                        <div class="operation-buttons">
                            <el-tooltip content="入库" placement="top" v-if="row.status !== '已完成'">
                                <el-button :icon="Check" circle type="success" @click="handleStockIn(row)" size="small" />
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </el-card>

        <!-- 入库对话框 -->
        <el-dialog 
            v-model="dialogVisible"
            title="商品入库"
            width="60%"
            destroy-on-close
            class="custom-dialog"
            :show-close="false"
        >
            <template #header>
                <div class="dialog-header">
                    <div class="dialog-title">
                        <el-icon class="title-icon"><Check /></el-icon>
                        <span>商品入库</span>
                    </div>
                    <el-button class="close-button" @click="dialogVisible = false" circle>
                        <el-icon><Close /></el-icon>
                    </el-button>
                </div>
            </template>
            
            <div class="dialog-content">
                <div class="order-header">
                    <div class="order-title">
                        <h2>入库信息</h2>
                        <el-tag :type="form.status === '已完成' ? 'success' : 'warning'">
                            {{ form.status }}
                        </el-tag>
                    </div>
                    <div class="order-number">
                        <span>订单编号：</span>
                        <span class="highlight">{{ form.orderNo }}</span>
                    </div>
                </div>
                
                <el-divider />
                
                <div class="info-section">
                    <h3>基本信息</h3>
                    <el-descriptions :column="2" border>
                        <el-descriptions-item label="供应商名称">{{ form.supplier }}</el-descriptions-item>
                        <el-descriptions-item label="入库人">{{ form.operator }}</el-descriptions-item>
                        <el-descriptions-item label="入库时间">{{ form.stockInTime ? formatDate(form.stockInTime) : '-' }}</el-descriptions-item>
                    </el-descriptions>
                </div>
                
                <div class="info-section">
                    <h3>商品明细</h3>
                    <el-table :data="form.details || []" style="width: 100%" border>
                        <el-table-column label="商品名称" prop="goodsName" align="center" min-width="150" />
                        <el-table-column label="数量" prop="quantity" width="100" align="center" />
                        <el-table-column label="单价" prop="price" width="100" align="center" />
                        <el-table-column label="总价" width="100" align="center">
                            <template #default="scope">
                                {{ (scope.row.quantity * scope.row.price).toFixed(2) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="存放位置" width="180" align="center">
                            <template #default="scope">
                                <el-input 
                                    v-model="scope.row.location" 
                                    placeholder="请输入存放位置"
                                    :disabled="form.status === '已完成'"
                                    class="location-input"
                                />
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                
                <div class="form-item">
                    <div class="form-label">备注</div>
                    <el-input
                        v-model="form.remark"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入备注信息"
                    />
                </div>
            </div>
            
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleSubmit" v-if="form.status !== '已完成'">
                        <el-icon><Check /></el-icon>确认入库
                    </el-button>
                    <el-button @click="dialogVisible = false">
                        <el-icon><Close /></el-icon>关闭
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {
    Search,
    Refresh,
    Check,
    Close
} from '@element-plus/icons-vue'
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils/format.js'
import { getStockInListService, stockInService } from '@/api/inventory.js'

// 搜索表单
const searchForm = reactive({
    orderNo: '',
    dateRange: []
})

// 表格数据
const tableData = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)

// 表单数据
const form = reactive({
    id: 0,
    orderNo: '',
    supplier: '',
    operator: '',
    status: '',
    stockInTime: null,
    remark: '',
    details: []
})

// 获取待入库订单列表
const getStockInList = async () => {
    try {
        const params = {
            pageNum: currentPage.value,
            pageSize: pageSize.value,
            orderNo: searchForm.orderNo,
            startTime: searchForm.dateRange?.[0],
            endTime: searchForm.dateRange?.[1]
        }
        const res = await getStockInListService(params)
        if (res.code === 0) {
            // 处理返回的数据，确保ID为数字类型
            tableData.value = res.data.items.map(item => ({
                ...item,
                id: parseInt(item.id),
                details: item.details.map(detail => ({
                    ...detail,
                    productId: parseInt(detail.productId)
                }))
            }))
            total.value = res.data.total
        }
    } catch (error) {
        console.error('获取待入库订单列表失败:', error)
        ElMessage.error('获取待入库订单列表失败')
    }
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    getStockInList()
}

// 重置表单
const resetForm = () => {
    searchForm.orderNo = ''
    searchForm.dateRange = []
    handleSearch()
}

// 入库
const handleStockIn = (row) => {
    dialogVisible.value = true
    // 确保ID为数字类型
    Object.assign(form, {
        ...row,
        id: parseInt(row.id),
        details: row.details.map(detail => ({
            ...detail,
            productId: parseInt(detail.productId)
        }))
    })
}

// 验证商品存放位置和备注
const validateLocations = () => {
    // 验证备注
    if (!form.remark) {
        ElMessage.warning('请输入备注信息')
        return false
    }
    
    // 验证存放位置
    const invalidItems = form.details.filter(item => !item.location)
    if (invalidItems.length > 0) {
        ElMessage.warning('请为所有商品设置存放位置')
        return false
    }
    return true
}

// 提交入库
const handleSubmit = async () => {
    try {
        // 验证存放位置
        if (!validateLocations()) return

        // 构建入库参数
        const stockInData = {
            orderId: form.id,
            orderNo: form.orderNo,
            remark: form.remark,
            details: form.details.map(item => ({
                productId: item.productId,
                productName: item.goodsName,
                quantity: item.quantity,
                price: item.price,
                location: item.location
            }))
        }

        // 调用入库接口
        const res = await stockInService(stockInData)
        if (res.code === 0) {
            ElMessage.success('入库成功')
            dialogVisible.value = false
            getStockInList() // 刷新列表
        } else {
            ElMessage.error(res.message || '入库失败')
        }
    } catch (error) {
        console.error('入库失败:', error)
        ElMessage.error('入库失败')
    }
}

// 分页相关方法
const handleSizeChange = (val) => {
    pageSize.value = val
    getStockInList()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    getStockInList()
}

// 页面加载时获取数据
onMounted(() => {
    getStockInList()
})
</script>

<style lang="scss" scoped>
.page-container {
    padding: 20px;
    
    .box-card {
        margin-bottom: 20px;
    }
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .title {
            font-size: 16px;
            font-weight: bold;
        }
    }
    
    .search-area {
        margin-bottom: 20px;
    }
}

.operation-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
}

.dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #e4e7ed;
    
    .dialog-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: bold;
        
        .title-icon {
            font-size: 20px;
            color: var(--el-color-primary);
        }
    }
}

.dialog-content {
    padding: 20px;
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .order-title {
        display: flex;
        align-items: center;
        gap: 15px;
        
        h2 {
            margin: 0;
            font-size: 20px;
            color: #303133;
        }
    }
    
    .order-number {
        font-size: 16px;
        color: #606266;
        
        .highlight {
            color: var(--el-color-primary);
            font-weight: bold;
        }
    }
}

.info-section {
    margin-bottom: 30px;
    
    h3 {
        margin: 0 0 15px 0;
        font-size: 16px;
        color: #303133;
    }
}

:deep(.el-descriptions) {
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

:deep(.el-table) {
    margin-top: 10px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.custom-input {
    width: 100%;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 20px;
    background-color: #fff;
    border-top: 1px solid #e4e7ed;
}

.form-item {
    margin-bottom: 20px;
    
    .form-label {
        margin-bottom: 8px;
        font-size: 14px;
        color: #606266;
    }
}

.location-input {
    width: 100%;
}
</style> 